﻿using System.Collections.Concurrent;

namespace _22_C_中线程安全的队列和栈
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "C#中线程安全的队列和栈";

            // 使用 Interlocked 来确保 num 的自增是线程安全的
            //int num = 0;
            //ConcurrentQueue<int> queues = new ConcurrentQueue<int>();

            //// 工作线程
            //Task task = Task.Run(() =>
            //{
            //    for (int i = 0; i < 10; i++)
            //    {
            //        int currentNum = Interlocked.Increment(ref num);
            //        queues.Enqueue(currentNum);
            //        Console.WriteLine("工作线程入队 " + currentNum);
            //    }
            //});

            //// 主线程
            //for (int i = 0; i < 10; i++)
            //{
            //    int currentNum = Interlocked.Increment(ref num);
            //    queues.Enqueue(currentNum);
            //    Console.WriteLine("主线程入队 " + currentNum);
            //}

            //// 等待工作线程完成
            ////task.Wait();

            //int ret = 0;
            //int count = queues.Count;

            //// 出队列
            //for (int i = 0; i < count; i++)
            //{
            //    bool bl = queues.TryDequeue(out ret);
            //    if (bl)
            //    {
            //        Console.WriteLine("出队列的数据 " + ret);
            //    }
            //}


            int num = 0;

            ConcurrentStack<int> stacks = new ConcurrentStack<int>();

            // 工作线程
            Task task = Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    int currentNum = Interlocked.Increment(ref num);
                    stacks.Push(currentNum);
                    Console.WriteLine("工作线程入队 " + currentNum);
                }
            });

            // 主线程
            for (int i = 0; i < 10; i++)
            {
                int currentNum = Interlocked.Increment(ref num);
                stacks.Push(currentNum);
                Console.WriteLine("主线程入队 " + currentNum);
            }

            int ret = 0;
            int count = stacks.Count;

            // 出队列
            for (int i = 0; i < count; i++)
            {
                bool bl = stacks.TryPop(out ret);
                if (bl)
                {
                    Console.WriteLine("出队列的数据 " + ret);
                }
            }

            Console.ReadKey();
        }
    }
}
